﻿using System.Reflection;
using Microsoft.EntityFrameworkCore;
using SBlogCore.Common.DatabaseAccessor.Attributes;

namespace SBlogCore.Common.DatabaseAccessor.Repositorys.EFCore
{
    public partial class Repository<TEntity>: IRepository<TEntity> where TEntity : class, IBaseEntity
    {
        private readonly dynamic _dbContext;

        public Repository(IServiceProvider provider)
        {
            Type entityType =typeof(TEntity);
            SDbContextAttribute entityAttribute = (entityType.GetInterface(nameof(IBaseEntity)) ?? throw new InvalidOperationException()).GetCustomAttribute<SDbContextAttribute>(true)!;
            Type contextType = entityAttribute.DbContextType;
            if (!contextType.IsAssignableTo(typeof(DbContext)))
            {
                throw new Exception("未注册正确的DbContext上下文");
            }
            _dbContext = provider.GetService(contextType)!;
            Entities = _dbContext.Set<TEntity>();
        }
        /// <summary>
        /// 实体
        /// </summary>
        public DbSet<TEntity> Entities { get; init; }
        /// <summary>
        /// 不跟踪实体
        /// </summary>
        public IQueryable<TEntity> DetachedEntities => Entities.AsNoTracking();

        public int SaveChanges()
        {
            return _dbContext.SaveChanges();
        }
        public Task<int> SaveChangesAsync(CancellationToken cancellationToken)
        {
            return _dbContext.SaveChangesAsync(cancellationToken);
        }
        public Task<int> SaveChangesAsync()
        {
            return _dbContext.SaveChangesAsync();
        }
    }
}
